<template>
  <div class="va-df-radiogroup">
    <input-radio v-for="cb in radioList" :key="cb.field.label" :disabled="cb.field.disabled" :field="cb.field" :value="value" @input="itemChange($event, cb)"></input-radio>
  </div>
</template>

<script>
  import _ from 'lodash'
  import InputRadio from './InputRadio.vue'

  /*
  * field配置
  *   itemLabelProp 如果不配置，是直接是dataSource项的值
  *   itemValueProp 如果不配置，是直接是dataSource项的值
  *   dataSource
  *   itemDisabled: function(item):boolean 可以通过此函数来决定哪些项是disabled的
  *   disabled
  * */
  export default {
    components: {InputRadio},
    props: {
      value: {
        default: false
      },
      disabled: {
        type: Boolean,
        default: false
      },
      dataSource: {
        type: Array,
        default () {
          return []
        }
      },
      field: {
        default () {
          return {}
        }
      }
    },
    data () {
      return {
        // {value, field}
        radioList: null
      }
    },
    mounted () {
      this.updateComponents()
    },
    methods: {
      itemChange (value, radio) {
        for (let r of this.radioList) {
          if (r.field.trueValue === value && r === radio) {
            this.$emit('input', value)
          }
        }
      },
      updateComponents () {
        if (this.dataSource && this.dataSource.length > 0 && this.radioList === null) {
          let list = []
          for (let item of this.dataSource) {
            let field = {}
            field.trueValue = this.field.itemValueProp ? _.get(item, this.field.itemValueProp) : item
            field.falseValue = undefined
            field.label = this.field.itemLabelProp ? _.get(item, this.field.itemLabelProp) : item
            if (_.isFunction(this.field.itemDisabled)) {
              field.disabled = this.disabled || this.field.itemDisabled(item)
            } else if (!_.isNil(this.field.itemDisabled)) {
              field.disabled = this.disabled || this.field.itemDisabled
            }
            list.push({field})
          }
          this.radioList = list
        }
      }
    },
    watch: {
      dataSource () {
        this.updateComponents()
      }
    }
  }
</script>

<style lang="stylus">
  .va-df-radiogroup
    .va-df-radio-wrapper
      &:not(:last-child)
        margin-right 10px
</style>
